<template>
  <div class="page chat-robot">
    <div class="chat-area">
      <div class="tip">
        <p>{{currentDate}}</p>
      </div>
      <div
        class="msg"
        v-for="(item, i) in dialogList"
        :key="i"
        :class="{ 'msg-send': item.type === 'send' }">
        <div class="msg-inner">
          <p>{{item.answer}}</p>
          <p v-if="item.type === 'receive'" class="recommand-title">{{langMap[currentLang].recommendIntro}}</p>
          <a
            v-for="(item2, i2) in item.relateList"
            :key="i2"
            @click="onRelateListClick(item2)">{{i2 + 1}}) {{item2.question}}</a>
        </div>
      </div>
    </div>
    <div id="bottomArea"></div>
    <div class="toolbar-area">
      <div class="toolbar-area-inner">
        <i
          class="icon"
          :class="{
            'icon-lang-en': currentLang === 'en',
            'icon-lang-zh': currentLang === 'zh'
          }"
          @click="onLangIconClick"></i>
        <div class="input-container">
          <input
            v-model="inputValue"
            type="text"
            confirm-type="send"
            :placeholder="langMap[currentLang].placeholder"
            :maxlength="100"
            :cursor-spacing="20"
            @input="onInputChange" />
        </div>
        <mp-button
          type="primary"
          size="normal"
          :disabled="sendBtnDisabled"
          @click="onSendBtnClick">{{langMap[currentLang].send}}</mp-button>
      </div>
    </div>
  </div>
</template>

<script>
import mixins from '@/mixins'
import mpButton from 'mpvue-weui/src/button'
import mpInput from 'mpvue-weui/src/input'

const langMap = {
  zh: {
    placeholder: '请输入您要咨询的问题',
    send: '发送',
    questionIntro: '您好，茫茫人海相遇是缘分，很高兴为您服务，您可直接输入问题或参考下方推荐进行自助服务噢！',
    recommendIntro: '为您推荐以下问题：'
  },
  en: {
    placeholder: 'Please enter your question',
    send: 'Send',
    questionIntro: 'Hello, I\'m glad to serve you. You can directly enter questions or refer to the recommendation below for self-service.',
    recommendIntro: 'The following questions are recommended:'
  }
}

export default {
  mixins: [mixins],
  components: {
    mpButton,
    mpInput
  },
  data () {
    return {
      inputValue: '',
      currentLang: 'zh',
      sendBtnDisabled: true,
      dialogList: [],
      relateList: [], // 相关的问题列表，默认为所有问题
      currentDate: '',
      langMap,
    }
  },
  mounted () {
    this.resetData()
    this.setDate()
    this.queryQuestionList()
  },
  methods: {
    /**
     * 查询问题列表，初始化时或者切换语言时
     * @param { boolean } init 是否初始化对话列表
     */
    async queryQuestionList (init = true) {
      const result = await this.$store.dispatch('selectRobotCustomerListByLanguage', {
        languageType: this.currentLang === 'zh' ? '1' : '2',
      })
      if (result && result.length > 0) {
        const relateList = []
        result.map((item, index) => {
          relateList.push({
            id: item.id,
            question: item.questionName
          })
        })
        // 初始化问题列表
        const dialogItem = {
          type: 'receive',
          answer: this.langMap[this.currentLang].questionIntro,
          relateList: relateList
        }
        if (init) {
          this.dialogList = []
          setTimeout(() => {
            wx.pageScrollTo({
              scrollTop: 0
            })
          })
          this.dialogList.push(dialogItem)
        } else {
          this.dialogList.push(dialogItem)
          setTimeout(() => {
            wx.pageScrollTo({
              selector: '#bottomArea'
            })
          })
        }
        this.relateList = relateList
      }
    },
    onLangIconClick () {
      if (this.currentLang === 'zh') {
        this.currentLang = 'en'
      } else {
        this.currentLang = 'zh'
      }
      this.queryQuestionList()
    },
    /**
     * 选中相关的问题
     */
    onRelateListClick (item) {
      const dialog = {
        type: 'send',
        answer: item.question
      }
      this.dialogList.push(dialog)
      setTimeout(() => {
        wx.pageScrollTo({
          selector: '#bottomArea'
        })
      })
      this.queryAnswer(item)
    },
    /**
     * 查询问题详情，包括相关推荐
     */
    async queryAnswer (item) {
      const result = await this.$store.dispatch('selectRobotCustomerById', {
        id: item.id
      })
      const relateList = this.relateList
      let newRelateList = []
      relateList.map((item2, index) => {
        if (item2.id !== item.id) {
          newRelateList.push(item2)
        }
      })
      const dialog = {
        type: 'receive',
        answer: result.answer,
        relateList: newRelateList
      }
      // 延迟1s显示查询结果，避免过快的体验
      setTimeout(() => {
        this.dialogList.push(dialog)
        setTimeout(() => {
          wx.pageScrollTo({
            selector: '#bottomArea'
          })
        })
      }, 1000)
    },
    /**
     * 发送咨询的问题
     */
    onSendBtnClick () {
      const value = this.inputValue
      if (!value) {
        return
      }
      const dialog = {
        type: 'send',
        answer: value
      }
      this.dialogList.push(dialog)
      this.inputValue = ''
      this.sendBtnDisabled = true
      setTimeout(() => {
        wx.pageScrollTo({
          selector: '#bottomArea'
        })
      })
      // 延迟1s查询问题，加上发送动画的0.3s，共1.3s
      setTimeout(() => {
        this.queryQuestionList(false)
      }, 1300)
    },
    /**
     * 控制发送按钮是否可以点击
     */
    onInputChange (e) {
      if (e.target.value) {
        this.sendBtnDisabled = false
      }
    },
    setDate () {
      const date = new Date()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()
      this.currentDate = `${month}-${day} ${hour}:${minute}`
    }
  }
}
</script>

<style lang="less">
.chat-robot {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  .chat-area {
    padding-bottom: 180rpx;
    .tip {
      text-align: center;
      padding: 30rpx 30rpx 0;
      p {
        display: inline-block;
        background-color: #c8c8c8;
        color: #fff;
        font-size: 26rpx;
        line-height: 44rpx;
        border-radius: 8rpx;
        padding: 0 10rpx;
        text-align: left;
      }
    }
    .msg {
      display: flex;
      justify-content: flex-start;
      font-size: 30rpx;
      line-height: 44rpx;
      color: #333;
      padding: 30rpx 100rpx 0 30rpx;
      &-inner {
        background-color: #fff;
        border: 1rpx solid #dcdbdb;
        border-radius: 20rpx 20rpx 20rpx 0;
        padding: 20rpx 20rpx;
        word-break: break-all;
      }
      &.msg-send {
        justify-content: flex-end;
        padding: 30rpx 30rpx 0 100rpx;
        .msg-inner {
          color: #fff;
          background-color: #488ff0;
          border: 1rpx solid #357ad9;
          border-radius: 20rpx 20rpx 0 20rpx;
        }
      }
      a {
        color: #488ff0;
      }
      .recommand-title {
        padding-top: 20rpx;
      }
    }
  }
  .toolbar-area {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #fff;
    border-top: 1rpx solid #dcdbdb;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    &-inner {
      display: flex;
      align-items: center;
      padding: 20rpx 20rpx;
    }
    .icon {
      width: 64rpx;
      height: 64rpx;
      background-repeat: no-repeat;
      background-position: center;
      background-size: contain;
      margin-right: 20rpx;
      &-lang-en {
        background-image: url("../../../static/images/lang-en.png");
      }
      &-lang-zh {
        background-image: url("../../../static/images/lang-zh.png");
      }
    }
    .input-container {
      flex: 1;
      box-sizing: border-box;
      padding: 20rpx 20rpx;
      background-color: #f3f3f3;
      border: 1rpx solid #dcdbdb;
      border-radius: 8rpx;
      input {
        font-size: 32rpx;
        color: #333;
      }
    }
    button {
      display: flex;
      align-items: center;
      margin-left: 20rpx;
      font-size: 32rpx;
      &[type=primary] {
        background-color: #488ff0;
      }
    }
  }
}
</style>
